package com.chushouya.manager.service.admin.impl;

import com.chushouya.common.util.CaptchaUtil;
import com.chushouya.manager.dto.admin.captcha.CaptchaDTO;
import com.chushouya.manager.service.admin.CaptchaService;
import com.general.framework.core.constant.Constants;
import com.general.framework.core.enums.LoginCodeEnum;
import com.general.framework.core.lang.IdTakes;
import com.general.framework.data.redis.RedisCache;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 系统访问日志情况信息 服务层处理
 */
@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private RedisCache redisCache;

    @Override
    public CaptchaDTO getCaptcha() {
        // 保存验证码信息
        String uuid = IdTakes.takeUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 获取运算的结果
        Captcha captcha = CaptchaUtil.getCaptcha();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        log.debug("captchaValue is {}", captchaValue);
        redisCache.setCacheObject(verifyKey, captchaValue, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        return new CaptchaDTO(uuid, captcha.toBase64());
    }
}
